const Model = require("redis-crud-fork");
const config = require("config");
const {RPCClient} = require("@alicloud/pop-core");
const Redis = require('redis')
const SmsCache = Model(Redis.createClient(Object.assign({db:4},config.get('redis'))),'Sms')
const sms_code_split=":"

const sendSms = async (phone,code)=>{
    let sms = {...config.get('sms')}
    sms.accessKeyId = process.env.smsAccessKeyId
    sms.accessKeySecret = process.env.smsAccessKeySecret
    const client = new RPCClient(sms);
    let params = {
        "RegionId": "Default",
        "PhoneNumbers": phone,
        "SignName": "智象科技",
        "TemplateCode": "SMS_181191316",
        "TemplateParam": "{code:" + code + "}"
    }
    await client.request('SendSms', params, {method: 'POST'})
}

const generateCode = async (phone)=>{
    let maxAge = config.get('sms.expiration'), code = Math.floor(Math.random()*9000) + 1000
    await SmsCache.insertEX({id:phone+sms_code_split+code,maxAge})
    if(config.get('sms.sendFlag')){
        await sendSms(phone, code)
    }
    return code
}

const getCache = async(phone,code)=>{
    let result = await SmsCache.get(phone+sms_code_split+code)
    return result
}

module.exports = {generateCode,getCache}
